#include "QCreateFromObjectOperation.h"
#include "Core/MainWindow.h"
#include <QMessageBox>
#include "FeatureShape/HistoryManager.h"
#include "FeatureShape/FeatureShape.h"
#include <TopExp_Explorer.hxx>


QCreateFromObjectOperation::QCreateFromObjectOperation(MainWindow* inMainWindow, ShapeOperation* inOperation, QWidget* parent)
	: QRSWidgetBase(inMainWindow, inOperation, parent)
	, ui(new Ui::QCreateFromObjectOperationClass())
{
	ui->setupUi(this);

	m_mainWindow->SetCanMultiSelect(false);

	connect(ui->modifyButton, &QPushButton::clicked, this, &QCreateFromObjectOperation::OnModify);
	connect(ui->confirmButton, &QPushButton::clicked, this, &QCreateFromObjectOperation::OnConfirm);
	connect(ui->cancelButton, &QPushButton::clicked, this, &QCreateFromObjectOperation::close);

	connect(m_mainWindow, &MainWindow::OnSelectedSubShapes, this, &QCreateFromObjectOperation::OnSelectedSubShapes);

	connect(ui->selectCombo, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &QCreateFromObjectOperation::OnTargetComboIndexChange);

	m_mainWindow->SetSelectionMode(SM_Edge);
}

QCreateFromObjectOperation::~QCreateFromObjectOperation()
{
	delete ui;
}

void QCreateFromObjectOperation::OnSelectedSubShapes(QIVtkSelectionPipeline* actor)
{
	m_selectedActor = actor;
}

void QCreateFromObjectOperation::closeEvent(QCloseEvent* event)
{
	disconnect(m_mainWindow, &MainWindow::OnSelectedSubShapes, this, &QCreateFromObjectOperation::OnSelectedSubShapes);

	m_mainWindow->SubWidgetClose(bIsConfirmed);
	m_mainWindow->SetCanMultiSelect(true);
}

void QCreateFromObjectOperation::OnModify()
{
	CreateInner();
}

void QCreateFromObjectOperation::OnConfirm()
{
	CreateInner();
	close();
}

void QCreateFromObjectOperation::OnTargetComboIndexChange(int index)
{
	if (index == 0)
	{
		m_mainWindow->SetSelectionMode(SM_Edge);
	}
    else if (index == 1)
	{
		m_mainWindow->SetSelectionMode(SM_Face);
	}
}

bool QCreateFromObjectOperation::CreateInner()
{
	std::vector<std::reference_wrapper<const TopoDS_Shape>> selectedShapes = m_mainWindow->GetSelectedShapes();
	if (!selectedShapes.size())
	{
        QMessageBox::warning(this, tr("Warning"), tr("请选择一个形状"));
		return false;
	}

	m_mainWindow->createBasicUnitActor(selectedShapes[0], true);
	m_mainWindow->ClearSelectedActors();

	int shapeIndex = GetIndexFromActor(m_mainWindow->GetCachedActors(), m_selectedActor);
	int subShapeIndex = -1;
	TopAbs_ShapeEnum shapeType = selectedShapes[0].get().ShapeType();
	int i = 0;
	TopExp_Explorer explorer(m_selectedActor->OccShape(), shapeType);
	while (explorer.More())
	{
		if (selectedShapes[0].get().IsEqual(explorer.Current()))
		{
			subShapeIndex = i;
			break;
		}

		explorer.Next();
		i++;
	}

	CreateShapeFromObjectOperatopn* op = new CreateShapeFromObjectOperatopn(QString("以object创建对象"), shapeIndex, subShapeIndex, shapeType == TopAbs_EDGE);
	m_mainWindow->GetHistoryManager()->applyOperation(op);

	return true;
}
